/*
 * 版权所有：义乌市路比信息科技有限公司
 * 作者：kinwyb<http://www.lcfgly.com>
 * 日期：2015-11-16
 */
package lcfgly.utils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.security.provider.SHA;

/**
 *
 * @author kinwyb<http://www.lcfgly.com>
 * @datetime 2015-11-16 9:08:59
 * @version 1.0
 */
public class Encode {

    /**
     * 编码类型
     */
    public enum Type {

        MD5,
        SHA,
        SHA1,
        SHA256
    }

    /**
     * HASH算法生成
     *
     * @param decript
     * @param type
     * @return
     * @throws NoSuchAlgorithmException
     * @throws java.io.UnsupportedEncodingException
     */
    @Deprecated
    public static String MessageDigest(String decript, Type type) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String codetype = "MD5";
        switch (type) {
            case MD5:
                decript = "MD5";
                break;
            case SHA:
                decript = "SHA";
                break;
            case SHA1:
                decript = "SHA-1";
                break;
            case SHA256:
                decript = "SHA-256";
                break;
            default:
                throw new NoSuchAlgorithmException();
        }
        MessageDigest digest = java.security.MessageDigest.getInstance(codetype);
        digest.update(decript.getBytes("UTF-8"));
        byte messageDigest[] = digest.digest();
        // Create Hex String
        StringBuilder hexString = new StringBuilder();
        // 字节数组转换为 十六进制 数
        for (int i = 0; i < messageDigest.length; i++) {
            String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexString.append('0');
            }
            hexString.append(shaHex);
        }
        return hexString.toString();
    }

    /**
     * md5加密方法
     *
     * @param source 源字符串
     * @return 加密后的字符
     * @throws NoSuchAlgorithmException
     */
    public static String md5(String source) throws NoSuchAlgorithmException {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'};
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(source.getBytes());
        byte[] tmp = md.digest();
        char[] str = new char[16 * 2];
        int k = 0;
        for (int i = 0; i < 16; i++) {
            byte byte0 = tmp[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }

}
